<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/13 0013
 * Time: 下午 3:24
 */
namespace app\admin\controller;

use app\common\BaseHelper;
use think\Db;
use think\Request;
use app\admin\model\Memberlevel;
use app\admin\model\Store;
use app\admin\model\Product;

/**
 * 加价换购
 * Class Repurchase
 * @package app\admin\controller
 */
class Repurchase extends Base{

    public function _initialize()
    {
        parent::_initialize();
        $this->defaultOrder = 'create_date DESC';
        if($this->request->action() == 'add' || $this->request->action() == 'edit'){
            // 会员等级
            $memberlevelList = Memberlevel::where(['status' => 1])->field('id, name')->select();
            // 门店
            $storeList = Store::where(['business_end_time' => ['gt', date('Y-m-d H:i:s')]])->field('id, name')->select();

            $this->assign('memberlevelList', $memberlevelList);
            $this->assign('storeList', $storeList);
        }

    }

    public function index(){
        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            $where['a.status'] = ['neq', 0];
            if(isset($param['name']) && $param['name']){
                $where['p.name'] = ['like', '%'.$param['name'].'%'];
            }
            $join = [
                ['__PRODUCT__ p','p.id=a.product_id']
            ];
            $field = 'a.*,p.name,p.price';
            $data = db('repurchase')->alias('a')->where($where)->join($join)->order('a.create_date DESC')->field($field)->limit($start, $length)->select();
            $count = count($data);
            foreach($data as $k => &$v)
            {
                if($v['to_user_type'] == 1){
                    $v['to_users'] = '全部用户';
                }else{
                    $member_level = explode(',',$v['to_users']);
                    $Memberlevel = Memberlevel::where('id','in',$member_level)->field('name')->select();
                    $v['to_users'] = '';
                    $i = 0;
                    foreach ($Memberlevel as $value){
                        if($i == 0){
                            $v['to_users'] .= $value['name'];
                        }else{
                            $v['to_users'] .= '、'.$value['name'];
                        }
                        $i++;
                    }
                }
                if($v['range'] == 1){
                    $v['store_ids'] = '线上线下全部门店';
                }elseif ($v['range'] == 2){
                    $v['store_ids'] = '线上门店';
                }else{
                    $store_ids = explode(',',$v['store_ids']);
                    $store = Store::where('id','in',$store_ids)->field('name')->select();
                    $v['store_ids'] = '';
                    $i = 0;
                    foreach ($store as $value){
                        if($i == 0){
                            $v['store_ids'] .= $value['name'];
                        }else{
                            $v['store_ids'] .= '、'.$value['name'];
                        }
                        $i++;
                    }
                }
            }
            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $data,
                'count' => $count,
            ];
            return json($result);
        }
        return $this->fetch($this->indexView,[
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    public function add(Request $request){
        return parent::add($request);
    }

    public function savePost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            $checkinfo = $this->checkparam($param);
            // 该商品是否已参加过其他活动
            $usedInfo = $this->isUsed($param['product_id']);
            if($usedInfo['code'] != 1){
                return $this->error($usedInfo['msg']);
            }
            if($checkinfo['pass']){
                $Repurchase = \app\admin\model\Repurchase::where('product_id',$param['product_id'])->find();
                if(empty($param['id']) && !$Repurchase){
                    //新增
                    $model = new \app\admin\model\Repurchase();
                    $id = BaseHelper::getUUID();
                    $param['id'] = $id;
                }else{
                    //修改
                    if($Repurchase){
                        $model =  $Repurchase;
                    }else{
                        $model = \app\admin\model\Repurchase::where('id',$param['id'])->find();
                    }
                }
                $param['threshold'] = $param['threshold']*100;
                $param['markup'] = $param['markup']*100;
                if($Repurchase){
                    unset($param['id']);
                    $result = $model->where('id',$Repurchase['id'])->update($param);
                }else{
                    $result = $model->save($param);
                }

                if ($result !== false) {
                    // 更新商品类型
                    $productRes = Product::where(['id' => $param['product_id']])->update(['type' => 3]);

                    return $this->success('操作成功');
                }
            }else{
                return $this->error($checkinfo['errmsg']);
            }
        }else{
            return $this->error('非法请求');
        }

    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model('repurchase');
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);
        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        $Product = Product::where('id', $info['product_id'])->field('name, price')->find();
        $info['product_name'] = $Product['name'];
        $info['product_price'] = sprintf("%.2f",$Product['price']/100);
        $info['threshold'] = $info['threshold']/100;
        $info['markup'] = $info['markup']/100;
        $info['store_ids'] = explode(',', $info['store_ids']);
        $info['to_users'] = explode(',', $info['to_users']);
        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * 启用/禁用
     */
    public function handle(Request $request){
        $model = model('repurchase');
        if ($request->isPost()) {
            $data = $request->param();
            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            if($result !== false) {
                return $this->success('操作成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $request = $this->request;
        $id = $request->param('id');

        $model = model($this->model);
        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        Db::startTrans();
        try {
            $result = $model->where('id', $id)->update(['status'=>0]);
            if ($result !== false) {
                // 更新商品类型
                $productRes = Product::where(['id' => $info['product_id']])->update(['type' => 0]);
                if ($productRes === false) {
                    Db::rollback();
                    return $this->error('更新商品类型失败');
                }

                // Query执行后的操作
                $model->_after_delete($id);

                $logInfo = $this->admin->name . '删除了1条' . lang($this->model) . '数据。';
                \app\common\Common::adminLog($request, $logInfo);

                Db::commit();
                return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                Db::rollback();
                return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
            }
        } catch (Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 是否被使用过
     */
    protected function isUsed($productId){
        if(!$productId){
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 该商品是否在限时特价活动中
        $flashsaleWhere['product_id'] = ['eq',$productId];
        $flashsaleWhere['status'] = ['neq',0];
        $flashsale = \app\admin\model\Flashsale::where($flashsaleWhere)->find();
        if($flashsale){
            return ['code' => 0, 'msg' => '该商品已在限时特价活动中，不能再参与此活动'];
        }

        // 该商品是否在买赠活动中
        $buygiftsWhere['buy_product_id'] = ['eq',$productId];
        $buygiftsWhere['status'] = ['neq',0];
        $buygifts = \app\admin\model\Buygifts::where($buygiftsWhere)->find();
        if($buygifts){
            return ['code' => 0, 'msg' => '该商品已在买赠活动中，不能再参与此活动'];
        }

        return ['code' => 1, 'msg' => ''];
    }

    /**
     * 检查购买商品是否在其它活动中使用过
     */
    public function checkUsed(){
        $productId = $this->request->param('product_id');
        $usedInfo = $this->isUsed($productId);

        return json($usedInfo);
    }

    /**
     * 选择商品
     */
    public function selectProducts(){
        $request = $this->request;
        $param = $request->param();

        if($request->isAjax()){
            $model = new Product();

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            $where = [
                'status' => 1
            ];
            if(isset($param['name']) && $param['name']){
                $where['name'] = ['like', '%'.$param['name'].'%'];
            }
            $fields = 'id, img_url, name, bar_code, category_id, purchase_price, price, wholesale_price, member_integral';
            $order = 'create_date DESC';
            $data = $model->where($where)->field($fields)->order($order)->limit($start, $length)->select();
            if($data){
                foreach ($data as $item) {
                    // 分类
                    $item['category_id'] = Productcategor::where('id', $item['category_id'])->value('name');
                    // 库存
                    $item['qty'] = $model->getStock($item['id']);
                }
            }
            $count = $model->where($where)->count();

            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return $this->view->fetch('repurchase/select_products', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * 参数校验
     * @param $param
     * @return array
     */
    private function checkparam($param){
        $checkinfo = [
            'pass' => true,
            'errmsg' => ''
        ];
        if(empty($param['product_id'])){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '商品不能为空';
        }
        if(!BaseCheckParam::CheckMoney($param['threshold'])){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '换购门槛金额不合法';
        }
        if(!BaseCheckParam::CheckMoney($param['markup'])){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '换购金额不合法';
        }
        if(!BaseCheckParam::GreaterZeroPositiveInteger($param['limit_num'])){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '限购数量不合法';
        }
        if($param['to_user_type'] !=1 && $param['to_user_type'] !=2){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '面向用户类型不合法';
        }
        if($param['to_user_type'] == 2){
            if(empty($param['to_users'])){
                $checkinfo['pass'] = false;
                $checkinfo['errmsg'] = '必须选择会员类型';
            }
        }
        if($param['range'] !=1 && $param['range'] !=2 && $param['range'] !=3){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '适用范围不合法';
        }
        if($param['range'] == 3){
            if(empty($param['store_ids'])){
                $checkinfo['pass'] = false;
                $checkinfo['errmsg'] = '必须选择门店';
            }
        }
        return $checkinfo;
    }
}